import {
	request
} from "@/utils/ajax.js"
import {amapKey} from "@/utils/constant.js"
const mapBase = "https://restapi.amap.com"


const regionMap = new Map()
// #ifdef H5
window.regionMap = regionMap
// #endif

const deepDistrict=(districts=[])=>{
	if(!districts||!districts.length){
		return
	}
	districts.forEach((dist)=>{
		if(regionMap.has(dist.adcode)){
			return
		}
		if(dist.districts&&dist.districts.length){
			regionMap.set(dist.adcode,dist.districts)
			deepDistrict(dist.districts)
		}
	})
}

export const district = async (keywords="100000",subdistrict=3)=>{
	if(regionMap.has(keywords)){
		return regionMap.get(keywords)
	}
	if(district.lock){
		throw new Error('正在请求中')
	}
	try{
		district.lock=true
		const {data:{districts},statusCode} = await request({
			url:mapBase+"/v3/config/district",
			method:'GET',
			data:{
				key:amapKey,
				keywords,
				subdistrict
			}
		})
		deepDistrict(districts)
		return regionMap.get(keywords);
	}catch(e){
		throw e
	}finally{
		district.lock = false
	}
}

	
export const regeo = async ({longitude,latitude})=>{
	if(!longitude||!latitude){
		throw new Error("参数错误")
	}
	const {data:{regeocode}} = await request({
		url:mapBase+"/v3/geocode/regeo",
		method:'GET',
		data:{
			key:amapKey,
			location:`${longitude},${latitude}`
		}
	})
	return regeocode
}
